var UglifyJS = require('uglify-js');
var Path = require('path');
var fs = require('fs');



function getJsonFiles(jsonPath) {

    let jsonFiles = [];

    function findJsonFile(path) {

        //读取文件中的文件名
        let files = fs.readdirSync(path);

        //item 文件名
        //index 相对性编号 从0开始
        files.forEach(function (item, index) {

            //字符串拼接
            let fPath = Path.join(path, item);
            //获取读取到的路径信息
            let stat = fs.statSync(fPath);
            //判断是文件夹就再次进行读写
            if (stat.isDirectory() === true) {
                findJsonFile(fPath);
            }
            //判断是文件 就将文件名添加到数组上
            if (stat.isFile() === true) {
                jsonFiles.push(fPath);
            }

        });

    }

    findJsonFile(jsonPath);

    console.log(jsonFiles);
    return jsonFiles;

}

//创建文件夹
function createFile(vaule){

    //先进行文件夹名去重

    var filename = [];//存放文件佳名称

    //获取文件夹姓名
    for (let a = 0; a < vaule.length; a++) {
        var splitfilename = vaule[a].split('\\');
        if(splitfilename.length !== 2){
            filename[a] = splitfilename[1];
        } 
        else{
            filename[a] = filename[a-1];
        }

    }

    //数组去重
    let set = new Set(filename);
    filename = Array.from(set);
    console.log('去重后文件夹名称:'+filename);

    

    //创建文件夹
    for (let b = 0; b < filename.length; b++) {

        // dist中文件夹名称及路径
        // Path.join(__dirname,'/dist/'+filename)

        fs.mkdir(Path.join(__dirname, '/dist/' + filename[b]), function (error) {
            if (error) {
                return console.log(error);
            }
            console.log('创建目录成功',Path.join(__dirname, '/dist/' + filename[b]));

            if(b === filename.length - 1){
                console.log('---------------创建文件夹完成-------------');

                //进行代码压缩
                yasuo(vaule);
            }

        });

        
    }

   
}

function yasuo(filename){

    
    for(let a = 0; a < filename.length; a++){
        fs.readFile(filename[a], (err, data) => {

            if (err) throw err;
    
            var writeFilename = filename[a].replace(/src/, "dist");
    
            //存放压缩后的代码
            var compressCode = UglifyJS.minify(data.toString());
    
            fs.writeFile(writeFilename, compressCode.code, (err) => {
                if (err) throw err;
    
                console.log(writeFilename, '文件已保存');

                if(a === filename.length -1){
                    console.log('------------压缩已完全完成----------');
                }

            });
        });
    }
}

var promise = new Promise(function (resoleve) {
    resoleve(getJsonFiles("src"));
});
promise.then(function (vaule) {  //vaule 是所有文件路径

    //创建文件夹
    createFile(vaule)
 
}).catch(function(err){
    console.log(err);
    
});







